import { AChannel } from "../Base/AChannel";
import { ServiceType } from "../Base/AService";
import { ErrorCode } from "../Base/ErrorCode";
import { IPEndPoint } from "../Base/IPEndPoint";
import { WebSocketHelper } from "./WebsocketHelper";
import { WService } from "./WService";

export class WChannel extends AChannel {
    private readonly Service: WService;
    private webSocket: WebSocket;
    constructor(id: Long, param2: IPEndPoint | WebSocket, service: WService) {
        super();
        this.Service = service;
        if (param2 instanceof IPEndPoint) {
            this.webSocket = new WebSocket(param2.toString());
        }
        else {
            this.webSocket = param2;
        }
        this.connectAsync();
    }
    private connectAsync() {
        this.webSocket.onopen = (e) => {
            console.log(e.AT_TARGET);
        };
        this.webSocket.onmessage = (e) => {
            this.OnRead(new DataView(e.data));
        };
    }
    public Send(actorId: Long, stream: DataView) {
        if (this.IsDisposed) {
            throw new Error("WChannel已经被Dispose, 不能发送消息");
        }
        switch (this.Service.ServiceType) {
            case ServiceType.Inner:
                // int messageSize = (int) (stream.Length - stream.Position);
                // if (messageSize > ushort.MaxValue * 16)
                // {
                //     throw new Exception($"send packet too large: {stream.Length} {stream.Position}");
                // }

                // this.sendCache.WriteTo(0, messageSize);
                // this.sendBuffer.Write(this.sendCache, 0, PacketParser.InnerPacketSizeLength);

                // // actorId
                // stream.GetBuffer().WriteTo(0, actorId);
                // this.sendBuffer.Write(stream.GetBuffer(), (int)stream.Position, (int)(stream.Length - stream.Position));
                break;
            case ServiceType.Outer:
                //stream.se
                break;
        }
    }
    private OnRead(memoryStream: DataView) {
        try {
            let channelId = this.Id;
            this.Service.OnRead(channelId, memoryStream);
        }
        catch (e) {
            console.error(`${this.RemoteAddress.toString()} ${memoryStream.byteLength} ${e}`);
            // 出现任何消息解析异常都要断开Session，防止客户端伪造消息
            this.OnError(ErrorCode.ERR_PacketParserError);
        }
    }

    private OnError(error: number) {
        console.error(`TChannel OnError: ${error} ${this.RemoteAddress}`);

        let channelId = this.Id;

        this.Service.Remove(channelId);

        this.Service.OnError(channelId, error);
    }
    public Dispose() {
        throw new Error("Method not implemented.");
    }
}
